package com.thermal.thermal_inspection.controller;

import com.thermal.thermal_inspection.common.CommonResponse;
import com.thermal.thermal_inspection.entity.Unit;
import com.thermal.thermal_inspection.service.UnitService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users/unit")
public class UnitController {
    @Autowired
    UnitService unitService;

    private static final Logger logger = Logger.getLogger(UnitController.class);

    /**
     * 新增机组
     */
    @PostMapping("/addUnit")
    public CommonResponse<Object> addUnit(@RequestParam String unitName){
        if(unitService.existUnitName(unitName)){
            logger.error("机组名已存在");
            return CommonResponse.createForError("机组名已存在");
        }
        int rows = unitService.addUnit(unitName);
        if(rows != 0) {
            logger.info("新增机组成功");
            return CommonResponse.createForSuccess("SUCCESS", null);
        }
        logger.error("新增机组失败");
        return CommonResponse.createForError("新增机组失败");
    }

    /**
     * 删除机组
     */
    @DeleteMapping("/deleteUnit")
    public CommonResponse<Object> deleteUnit(@RequestParam int unitId){
        String selectMsg = unitService.isUseUnit(unitId);
        if (selectMsg != null)
            return CommonResponse.createForError(selectMsg);
        int rows = unitService.deleteUnit(unitId);
        if(unitId != 0) {
            logger.info("删除机组成功");
            return CommonResponse.createForSuccess("SUCCESS", null);
        }
        logger.error("删除机组失败");
        return CommonResponse.createForError("删除机组失败");
    }

    /**
     * 查找所有机组
     */
    @GetMapping("/getUnits")
    public CommonResponse<List<Unit>> getUnits(){
        List<Unit> unitList = unitService.getUnits();
        if(!unitList.isEmpty()) {
            logger.info("查找机组成功");
            return CommonResponse.createForSuccess("SUCCESS", unitList);
        }
        logger.error("机组列表为空");
        return CommonResponse.createForError("机组列表为空");
    }

    /**
     * 修改机组名字
     */
    @PutMapping("/updateUnit")
    public CommonResponse<Object> updateUnit(@RequestParam int unitId, @RequestParam String unitName){
        if(!unitService.existUnit(unitId)) {
            logger.error("修改机组名失败，该机组不存在");
            return CommonResponse.createForError("修改机组名失败，该机组不存在");
        }
        if(unitService.existUnitName(unitName)){
            logger.error("机组名已存在");
            return CommonResponse.createForError("机组名已存在");
        }
        int rows = unitService.updateUnit(unitId, unitName);
        if(rows != 0) {
            logger.info("修改机组名成功");
            return CommonResponse.createForSuccess("SUCCESS", null);
        }
        logger.error("修改机组名失败");
        return CommonResponse.createForError("修改机组名失败");
    }
}
